<template>
    <!-- 主内容区域 -->
    <div class="w-full max-h-fit pt-[10%]">
        <div class="flex justify-center items-center h-fit max-h-fit flex-col">
            <div
                class="w-full max-w-lg p-4 bg-white border border-gray-200 rounded-lg shadow sm:p-6 md:p-8 dark:bg-gray-800 dark:border-gray-700">
                <div class="text-xl font-semibold text-center mb-2 text-gray-900 dark:text-gray-300">
                    <img :src="blogSettingsStore.blogSettings.logo" class="h-14 mr-2 inline" alt="wjblog Logo" />

                    <div class="text-lg font-semibold">用户登录中心</div>
                </div>
                <div class="p-4 md:p-5">
                    <!-- 引入 Element Plus 表单组件，移动端设置宽度为 5/6，PC 端设置为 2/5 -->
                    <el-form class="space-y-4" ref="formRef" :rules="rules" :model="loginForm">
                        <el-form-item prop="username">
                            <!-- 输入框组件 -->
                            <label for="username"
                                class="block mb-2 text-sm font-semibold text-gray-900 dark:text-gray-300">用户名</label>
                            <el-input size="large" v-model="loginForm.username" placeholder="请输入用户名" :prefix-icon="User"
                                clearable />
                        </el-form-item>
                        <el-form-item prop="password">
                            <!-- 密码框组件 -->
                            <label for="password"
                                class="block mb-2 text-sm font-semibold text-gray-900 dark:text-gray-300">密码</label>
                            <el-input size="large" type="password" v-model="loginForm.password" placeholder="请输入密码"
                                :prefix-icon="Lock" clearable show-password />
                        </el-form-item>

                        <div class="flex justify-between">
                            <div class="flex items-start">
                                <div class="flex items-center h-5">
                                    <input id="remember" type="checkbox" value=""
                                        class="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-blue-300 dark:bg-gray-600 dark:border-gray-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 dark:focus:ring-offset-gray-800"
                                        required />
                                </div>
                                <label for="remember"
                                    class="ms-2 text-sm font-medium text-gray-900 dark:text-gray-300">记住我</label>
                            </div>
                            <a @click="userArtificial" data-tooltip-target="tooltip-remember" data-tooltip-placement="top" class="text-sm text-blue-700 hover:underline dark:text-blue-500">忘记密码?</a>
                            <div id="tooltip-remember" role="tooltip"
                                class="absolute z-10 invisible inline-block px-3 py-2 text-xs font-medium text-white transition-opacity duration-300 bg-gray-900 rounded shadow-sm opacity-0 tooltip dark:bg-gray-700">
                                请以【找回密码+用户名】作为邮件标题，内容至少包括用户名，绑定的手机号，QQ号，邮箱（如未绑定可省略），新密码等个人信息，信息越完整成功概率越高，发送邮件至 <a>weijianhuawen@163.com</a>
                                <div class="tooltip-arrow" data-popper-arrow></div>
                            </div>
                        </div>
                        <div class="text-sm text-center pt-3"> 注册即表示您同意并愿意遵守 <a
                                class="font-medium text-blue-600 dark:text-blue-500 hover:underline"
                                @click="router.push('/agreement')">用户协议</a> 与 <a
                                class="font-medium text-blue-600 dark:text-blue-500 hover:underline"
                                @click="router.push('/privacy')">隐私政策</a></div>
                        <el-form-item>
                            <!-- 登录按钮，宽度设置为 100% -->
                            <el-button class="w-full mt-2 dark:text-gray-100" size="large" type="primary"
                                :loading="loading" @click="userLogin">登录</el-button>
                        </el-form-item>
                        <!-- <button type="submit" @click="userLogin"
                            class="w-full text-white bg-sky-600 font-medium hover:bg-sky-700 focus:ring-4 focus:outline-none focus:ring-sky-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-sky-500 dark:hover:bg-sky-600 dark:focus:ring-sky-800">
                            登录
                        </button> -->
                        <div class="text-sm font-medium text-gray-500 dark:text-gray-300">
                            没有账户? <a @click="registerUser"
                                class="text-blue-700 hover:underline dark:text-blue-500">注册账户</a>
                        </div>
                    </el-form>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
// 引入 Element Plus 中的用户、锁图标
import { User, Lock, Checked, Avatar, Message, UserFilled, EditPen, ChatRound, Phone, Location, School } from '@element-plus/icons-vue'
import {ref, reactive, onMounted, onBeforeUnmount} from 'vue'
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { showMessage, showModel } from '@/composables/utils';
import { getToken, setToken } from '@/composables/auth';
import { useUserStore } from '@/stores/user';
import { login } from '@/api/frontend/user';
import { uploadFile } from '@/api/frontend/file';
import { useBlogSettingsStore } from '@/stores/blogsettings';
import { initFlowbite, initTooltips } from 'flowbite';

// 初始化 Flowbit 组件
onMounted(() => {
    initFlowbite()
    initTooltips()
})

const userStore = useUserStore()
const router = useRouter()
const loginForm = ref({
    username: '',
    password: ''
})
const blogSettingsStore = useBlogSettingsStore()
const formRef = ref(null)
//表单验证规则
const rules = {
    username: [
        {
            required: true,
            message: "用户账号不能为空！",
            trigger: "blur"
        }
    ],
    password: [
        {
            required: true,
            message: "密码不能为空！",
            trigger: "blur"
        }
    ]
}
// 确认用户登录桩体
const confirmLogin = () => {
    let tmpUserStore = useUserStore()
    let tk = Object.keys(tmpUserStore.userInfo)
    let token = getToken()
    return tk.length > 0 || token
}

const userArtificial = () => {
    showModel(
        "请以【找回密码+用户名】作为邮件标题，内容至少包括用户名，绑定的手机号，QQ号，邮箱（如未绑定可省略），新密码等个人信息，信息越完整成功概率越高，发送邮件至weijianhuawen@163.com，我们将在15个工作日内将处理结果通过邮件告知您！",
        "null",
        "联系管理员",
        true
    ).then(() => {
        console.log("找回密码")
    }).catch(() => {
        console.log("找回密码")
    })
}

//登录加载按钮
const loading = ref(false)
const isLogined = ref(false)
const userLogin = () => {
    console.log("用户登录")
    //先验证表单字段是否合法
    formRef.value.validate((valid) => {
        if (!valid) {
            console.log("表单验证参数不合法")
            return false
        }
        //开始加载
        loading.value = true
        let params = {
            "username": loginForm.value.username,
            "password": loginForm.value.password
        }
        login(params).then((res) => {
            if (res.success == true) {
                //提示登录成功
                showMessage("您好！" + loginForm.value.username + "，登录成功！")
                //将token保存到cookie
                let token = res.data.token
                setToken(token)
                //获取用户信息
                userStore.setUserInfo()
                // 设置为登录状态
                isLogined.value = true
                // 跳转到首页
                router.push({ path: '/safeguard/user/person/center'})
            } else {
                //提示登录失败
                let message = res.message
                ElMessage({
                    message: message,
                    type: "error"
                })
            }
        }).finally(() => {
            //结束加载
            loading.value = false
        })
    })
}

onMounted(() => {
    // 检查用户是否登录
    if (confirmLogin() || isLogined.value) {
        // 如果已经登录，则跳转到个人主页
        router.push({ path: '/user/person/' + userStore.userInfo.userId})
    }
})

const registerUser = () => {
    // 跳转到注册页面
    router.push({ path: '/user/register' })
}

// 按回车键后，执行注册事件
function onKeyUp(e) {
    console.log(e)
    if (e.key == 'Enter') {
        userLogin()
    }
}

// 添加键盘监听
onMounted(() => {
    console.log('添加键盘监听')
    document.addEventListener('keyup', onKeyUp)
})

// 移除键盘监听
onBeforeUnmount(() => {
    document.removeEventListener('keyup', onKeyUp)
})

</script>

<style scoped>
.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}

.demo-date-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}

.demo-date-picker .block:last-child {
  border-right: none;
}

.demo-date-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-show {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.basic {
  flex: 1;
}
</style>

<style></style>